package com.cjzuji.rental.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cjzuji.rental.Bean.AiZuJiRequest;
import com.cjzuji.rental.Config.AZJConfig;
import com.cjzuji.rental.dao.*;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.OrderBill;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.service.AiZuJiService;
import com.cjzuji.rental.util.Tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cjzuji.rental.dao.AiZuJiBillDao;
import com.cjzuji.rental.dao.AiZuJiContractDao;
import com.cjzuji.rental.dao.AiZuJiOrderDao;
import com.cjzuji.rental.dao.AiZuJiUserDao;

import java.util.*;

@Service
public class AiZuJiServiceImpl implements AiZuJiService {
    @Autowired
    AiZuJiOrderDao aiZuJiOrderDao;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderBillMapper orderBillMapper;
    @Autowired
    AiZuJiUserDao aiZuJiUserDao;
    @Autowired
    AiZuJiContractDao aiZuJiContractDao;
    @Autowired
    AiZuJiBillDao aiZuJiBillDao;
    @Autowired
    AZJConfig azjConfig;

    private static final Logger logger = LoggerFactory.getLogger(AiZuJiServiceImpl.class);
    @Override
    @Transactional
    public List<Map<String, Object>> getAiZuJiList(String azjtk){
        String url = azjConfig.getGetListUrl();
        AiZuJiRequest aiZuJiRequest = new AiZuJiRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        aiZuJiRequest.setCurrPage(1);
        aiZuJiRequest.setOtherProxyOrder(0);
        aiZuJiRequest.setOverTimeSendOut(0);
        aiZuJiRequest.setPageSize(20);
        aiZuJiRequest.setProxyOrder(0);
        aiZuJiRequest.setReviewedFlag(false);
        aiZuJiRequest.setSupplyOrder(0);
        int pageNum = 1;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                aiZuJiRequest.setCurrPage(pageNum);
                String json = objectMapper.writeValueAsString(aiZuJiRequest);
                String resStr = Tool.request(url,"", "", json,"", azjtk);
                //logger.info("获取请求结果 {}",resStr);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                logger.info("res {}",res);
                // 获取 data → list
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                //logger.info("dataMap {}",dataMap);
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("data");
                //logger.info("list {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                       // System.out.println("item~~~~~~~~~~~"+item.toString());
                        String rentRecrdNo = item.get("rentRecordNo").toString();
                        //查询订单详情
                        Map<String,Object> orderDetail = getOrderDetailes(azjtk, rentRecrdNo);
                        //logger.info("orderDetail {}",orderDetail);
                        //明细，碎屏险
                        int screenStr = 0;
                        double screenRisksAmount = 0.0;
                        double discountAmount = 0.0;
                        List<Map<String,Object>> orderScreenRisks = getScreenRisks(azjtk, rentRecrdNo);
                        //logger.info("orderScreenRisks {}",orderScreenRisks);
                        if (orderScreenRisks != null && !orderScreenRisks.isEmpty()) {
                            for (Map<String, Object> orderScreenRisk:orderScreenRisks){
                                //logger.info("accountCodeVal {}",orderScreenRisk.get("accountCodeVal").toString());
                                if (orderScreenRisk.containsKey("accountCodeVal") && "碎屏保障".equals(orderScreenRisk.get("accountCodeVal").toString())) {
                                    screenStr = 1;
                                    screenRisksAmount = Double.parseDouble(orderScreenRisk.get("amount").toString());
                                }
                                if (orderScreenRisk.containsKey("accountCodeVal") && "二次分单首期款优惠".equals(orderScreenRisk.get("accountCodeVal").toString())){
                                    discountAmount = Double.parseDouble(orderScreenRisk.get("amount").toString());
                                }
                            }
                        }
                        //合同list
                        List<Map<String,Object>> ordercontract = getContractList(azjtk,rentRecrdNo);
                        //logger.info("ordercontract {}",ordercontract);
                        String orderNo = item.get("rentRecordNo").toString();
                        // 判断 当前的订单号是否在数据库中存在 如果存在  跳出当前循环
                        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("order_id",orderNo);
                        List<Orders> existingOrder = orderMapper.selectList(queryWrapper);
                        //logger.info("existingOrder {}",existingOrder);
                        if (existingOrder.size() > 0 ) {
                            // 订单已存在
                            logger.info("订单已存在~~");
                        }
                        else{
                            Long orderID = aiZuJiOrderDao.save(item,orderDetail,screenStr,screenRisksAmount,discountAmount);
                            //System.out.println("进去开始保存user~~~~~~~~~~~~~~"+orderID);
                            aiZuJiUserDao.save(orderDetail,orderID);
                            //stateName=待归还，有合同，账单信息表
                            //logger.info("打印orderDetail {}",orderDetail);
                            if(item.containsKey("stateName")) {
                                if ("待归还".equals(item.get("stateName").toString())||"已完成".equals(item.get("stateName").toString())) {
                                    //有合同List
                                    System.out.println("进去开始保存contract~~~~~~~~~~~~~~"+orderID);
                                    aiZuJiContractDao.save(ordercontract,orderID);
                                    //账单list
                                    Map<String,Object> billMap = getBillList(azjtk,rentRecrdNo);
                                    String totalLateFeeS = billMap.get("totalLateFee").toString();
                                    Double totalLateFee = Double.parseDouble(totalLateFeeS);
                                    List<Map<String, Object>> orderBill = (List<Map<String, Object>>) billMap.get("list");
                                   // logger.info("orderBill {}",orderBill);
                                    if (orderBill.size() > 0) {
                                        System.out.println("进去开始保存bill~~~~~~~~~~~~~~"+orderID);
                                        aiZuJiBillDao.save(orderBill, orderID, orderNo,totalLateFee);
                                        System.out.println("保存成功~~~~~~~~~~~~~~~~~~s"+orderID);
                                    }
                                }

                            }
                        }
                    }
                }
                else {
                    break;
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //租用中
    @Override
    @Transactional
    public List<Map<String, Object>> upDateBill(String azjtk){
        String url = azjConfig.getGetListUrl();
        AiZuJiRequest aiZuJiRequest = new AiZuJiRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        aiZuJiRequest.setCurrPage(1);
        aiZuJiRequest.setOtherProxyOrder(0);
        aiZuJiRequest.setOverTimeSendOut(0);
        aiZuJiRequest.setPageSize(20);
        aiZuJiRequest.setProxyOrder(0);
        aiZuJiRequest.setReviewedFlag(false);
        aiZuJiRequest.setSupplyOrder(0);
        aiZuJiRequest.setStates("10,40,42,45,48,24,44,25,15,43,41,46");
        int pageNum = 1;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                aiZuJiRequest.setCurrPage(pageNum);
                String json = objectMapper.writeValueAsString(aiZuJiRequest);
                String resStr = Tool.request(url,"", "", json,"", azjtk);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("data");
                //logger.info("list {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        //System.out.println("item~~~~~"+item.toString());
                        String rentRecrdNo = item.get("rentRecordNo").toString();
                        //查询订单详情
                        Map<String,Object> orderDetail = getOrderDetailes(azjtk, rentRecrdNo);
                        //logger.info("orderDetail {}",orderDetail);
                        //合同list
                        List<Map<String,Object>> ordercontract = getContractList(azjtk,rentRecrdNo);
                        String orderNo = item.get("rentRecordNo").toString();
                        //账单list
                        Map<String,Object> billMap = getBillList(azjtk,rentRecrdNo);
                        String totalLateFeeS = billMap.get("totalLateFee").toString();
                        Double totalLateFee = Double.parseDouble(totalLateFeeS);
                        List<Map<String, Object>> orderBill = (List<Map<String, Object>>) billMap.get("list");
                        // logger.info("orderBill {}",orderBill);
                        //更新orders表的状态为3,更新快递单号，更新时间
                        UpdateWrapper<Orders> updataWrapper = new UpdateWrapper<>();
                        updataWrapper.eq("order_id",rentRecrdNo)
                                .set("status",3)
                                .set("delivery_no", item.get("logisticsNo").toString())
                                .set("update_time",new Date());
                        orderMapper.update(updataWrapper);
                        // 判断 当前的订单号是否在数据库中存在 如果存在  跳出当前循环
                        QueryWrapper<OrderBill> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("orders_id",orderNo);
                        List<OrderBill> existingBill = orderBillMapper.selectList(queryWrapper);
                        logger.info("查询到的已存在账单数量: {}",existingBill.size());
                        // 订单已存在
                        if (!existingBill.isEmpty() ) {
                            Long orderID = existingBill.get(0).getOrderId();
                            // 订单已存在，对比两方的“还款状态”数据，如果相同不变，不同对数据库账单表进行更新
                            logger.info("订单已存在~~,对比更新数据",orderNo);
                            compareUpdate(orderBill,existingBill,orderID);
                        }
                        else{
                            QueryWrapper<Orders> orderWrapper = new QueryWrapper<>();
                            orderWrapper.eq("order_id",orderNo);
                            Orders order = orderMapper.selectOne(orderWrapper);
                            if(order != null){
                                Long orderID = order.getId();
                                logger.info("添加合同表~~",orderNo);
                                aiZuJiContractDao.save(ordercontract,orderID);
                                logger.info("添加账单表~~",orderNo);
                                aiZuJiBillDao.save(orderBill, orderID, orderNo,totalLateFee);
                            }else {
                                logger.info("Orders表中未找到订单~~~",orderNo);
                            }
                        }
                    }
                }
                else {
                    break;
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //逾期
    @Override
    @Transactional
    public List<Map<String, Object>> getOverdue(String azjtk){
        String url = azjConfig.getGetListUrl();
        AiZuJiRequest aiZuJiRequest = new AiZuJiRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        aiZuJiRequest.setCurrPage(1);
        aiZuJiRequest.setOtherProxyOrder(0);
        aiZuJiRequest.setOverTimeSendOut(0);
        aiZuJiRequest.setPageSize(20);
        aiZuJiRequest.setProxyOrder(0);
        aiZuJiRequest.setReviewedFlag(false);
        aiZuJiRequest.setSupplyOrder(0);
        aiZuJiRequest.setStates("15,41,43,25,47,46");
        int pageNum = 1;
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                aiZuJiRequest.setCurrPage(pageNum);
                String json = objectMapper.writeValueAsString(aiZuJiRequest);
                String resStr = Tool.request(url,"", "", json,"", azjtk);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                //logger.info("res {}",res);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                //logger.info("dataMap {}",dataMap);
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("data");
                //logger.info("list {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        //System.out.println("item~~~~~"+item.toString());
                        String rentRecrdNo = item.get("rentRecordNo").toString();
                        // 判断 当前的订单号是否在数据库中存在 如果存在  跳出当前循环
                        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("order_id",rentRecrdNo);
                        List<Orders> existingOrder = orderMapper.selectList(queryWrapper);
                        // 订单已存在
                        if (!existingOrder.isEmpty() ) {
                            // 订单已存在，更新该订单在Orders表中的状态为4 逾期
                            logger.info("订单已存在~~,更新状态",rentRecrdNo);
                            UpdateWrapper<Orders> updataWrapper = new UpdateWrapper<>();
                            updataWrapper.eq("order_id",rentRecrdNo)
                                    .set("status",4)
                                    .set("update_time",new Date());
                            orderMapper.update(updataWrapper);

                        }
                        else{
                            logger.info("Orders表中未找到订单~~~",rentRecrdNo);
                        }
                    }
                }
                else {
                    break;
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //查询订单详情
    public Map<String,Object> getOrderDetailes(String azjtk, String rentRecordNo) throws JsonProcessingException {
        System.out.println("azjtk~~~~~"+azjtk);
        //查询订单详情（rentRecordNo动态传递）
        String detail = azjConfig.getGetDetailUrl()+rentRecordNo;
        String detailStr =  Tool.getRequest(detail,"","",azjtk);
        ObjectMapper resDetailMapper = new ObjectMapper();
        Map<String,Object> resDel = resDetailMapper.readValue(detailStr,Map.class);
        Map<String,Object> detailMap = (Map<String, Object>) resDel.get("data");
        //System.out.println("订单详情~~~~~"+detailMap);
        return detailMap;
    }
    //合同详情
    public List<Map<String,Object>> getContractList(String azjtk, String rentRecordNo) throws JsonProcessingException {
        // 请求参数带上，
        AiZuJiRequest aiZuJiRequest = new AiZuJiRequest();
        aiZuJiRequest.setRentRecordNo(rentRecordNo);
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String JSON = objectMapper.writeValueAsString(aiZuJiRequest);
        String contractUrl = azjConfig.getGetContractUrl() ;
        String contractStr =  Tool.request(contractUrl,"","", JSON,"",azjtk);
        ObjectMapper rescontractMapper = new ObjectMapper();
        Map<String,Object> resCon=rescontractMapper.readValue(contractStr,Map.class);
        // 根据情况可能是List，可能是Map：合同详情~~~~~{data=[{，data是List，那就List,{data={}那就是Map
        List<Map<String,Object>> contractList = (List<Map<String,Object>>) resCon.get("data");
        //System.out.println("合同详情~~~~~"+contractList);
        return contractList;
    }
    //账单详情
    public Map<String, Object> getBillList(String azjtk,String orderSN) throws JsonProcessingException {
        System.out.println("orderSN~~~~~~"+orderSN);
        AiZuJiRequest aiZuJiRequest = new AiZuJiRequest();
        aiZuJiRequest.setOrderSN(orderSN);
        ObjectMapper objectMapper = new ObjectMapper();
        String JSON=objectMapper.writeValueAsString(aiZuJiRequest);
        String billUrl = azjConfig.getGetBillUrl() ;
        String billStr =  Tool.request(billUrl, "","",JSON,"",azjtk);
        //System.out.println("账单详情~~~~~"+billStr);
        ObjectMapper resbillMapper = new ObjectMapper();
        Map<String,Object> resBill=resbillMapper.readValue(billStr,Map.class);
        Map<String, Object> billMap = (Map<String, Object>) resBill.get("data");
        return billMap;
    }
    //明细详情，碎屏险
    public List<Map<String,Object>> getScreenRisks(String azjtk,String orderSN) throws JsonProcessingException {
        AiZuJiRequest aiZuJiRequest = new AiZuJiRequest();
        aiZuJiRequest.setOrderSN(orderSN);
        ObjectMapper objectMapper = new ObjectMapper();
        String JSON=objectMapper.writeValueAsString(aiZuJiRequest);
        String screenUrl = "https://external-gw.woaizuji.com/merchantTeamwork/inside_route_page/merchantAccountInfo/accountRecord/queryInAccountRecord";
        String screenStr =  Tool.request(screenUrl, "","",JSON,"",azjtk);
        //System.out.println("碎屏险详情~~~~~"+screenStr);
        ObjectMapper resscreenMapper = new ObjectMapper();
        Map<String,Object> resscreen=resscreenMapper.readValue(screenStr,Map.class);
        List<Map<String,Object>> screenMap = (List<Map<String,Object>>) resscreen.get("data");
        //System.out.println("碎屏险详情~~~~~"+screenMap);
        return screenMap;
    }

    //对比更新代码
    public void compareUpdate(List<Map<String, Object>> billDtoList,List<OrderBill> existingBill, Long orderID) {
        System.out.println("billDtoList~~:"+billDtoList);
        //创建一个Map，用于存储数据库中的账单
        Map<Integer, OrderBill> existingBillMap = new HashMap<>();
        for (OrderBill bill : existingBill) {
            existingBillMap.put(bill.getTerm(), bill);
        }
        //logger.info("existingBillMap {}",existingBillMap);
        for (Map<String, Object> billDto : billDtoList) {
            Integer term = (Integer) billDto.get("repayPeriods");
            String newStatus = billDto.get("settleStatuStr") != null ? billDto.get("settleStatuStr").toString() : "";
            OrderBill oldBill = existingBillMap.get(term);
            if (oldBill != null) {
                //对比订单状态
                String oldStatus = oldBill.getRepayStatusStr() != null ? oldBill.getRepayStatusStr() : "";
                //System.out.println("oldStatus~~ " + oldStatus);
                if(!newStatus.equals(oldStatus)){
                    //状态不同
                    logger.info("状态不同，第{}期~~", term);
                    UpdateWrapper<OrderBill> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", oldBill.getId())
                            .set("real_pay_time", billDto.get("repaymentTime")) //支付时间
                            .set("real_pay_capital", billDto.get("alreadyRepayAmount"))  //还款金额
                            .set("repay_status_str", newStatus) // 还款状态
                            .set("real_repay_time", billDto.get("repaymentTime"))//还款时间
                            .set("update_time", new Date());
                    orderBillMapper.update(null,updateWrapper);
                }else {
                    //logger.info("状态相同，第{}期~~", term);
                }
            }
        }
    }

}
